package booksystem.controller;


import booksystem.dao.BookDao;
import booksystem.dao.impl.BookDaoImpl;
import booksystem.entity.Book;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@WebServlet(name="BookServlet", urlPatterns = "/book")
public class BookServlet extends BaseServlet {
    private BookDao bookDao = new BookDaoImpl();

    // 获取某个图书详情接口
    public void detail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String book_id = req.getParameter("bid");
        // 根据图书 id 获取到图书的详细信息
        Book book_detail = bookDao.getBookDetail(book_id);

        // 随机获取所有图书中的某几条数据
        List<Book> allBook = bookDao.getAllBook();

        //把随机取得的数据存储在 listRandom 中
        List<Book> random_book = new ArrayList<Book>();
        //随机取出n条不重复的数据,这里我设置随机取3条数据
        for (int i = 5; i >=1; i--) {
            Random random = new Random();
            //在数组大小之间产生一个随机数 j
            int j = random.nextInt(allBook.size());
            //取得list 中下标为j 的数据存储到 listRandom 中
            random_book.add((Book) allBook.get(j));
            //把已取到的数据移除,避免下次再次取到出现重复
            allBook.remove(j);
        }

        // 将图书详情传到前端页面
        req.setAttribute("book_detail", book_detail);
        req.setAttribute("random_book", random_book);
        req.getRequestDispatcher("/book_detail.jsp").forward(req, resp);
    }

    /*
     * 获取某个类别的图书
     * */
    public void getClassifyBook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取当前类别的图书
        String classify = req.getParameter("classify");
        List<Book> book_list = bookDao.getClassifyBook(classify);
//        System.out.println(classify);
        req.setAttribute("bookList", book_list);
        req.getRequestDispatcher("/index.jsp").forward(req, resp);
    }
}
